package com.sbck.cs3.MyClass;

import android.graphics.Color;
import android.util.Log;

import com.sbck.cs3.MyGlobal;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketUtil {

    private Socket cSocket;
    private ExecutorService cExecutorService;

    public RecvDataThread cRecvDataThread;

    public SocketUtil()
    {
        cExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    }

    @Override
    protected void finalize()
    {
    }
    public void startClient()
    {
        if(cSocket == null)
        {
            Runnable runnable = new Runnable()
            {
                @Override
                public void run()
                {
                    String ip="";
                    int port = 0;
                    try
                    {
                        Log.i("tcp", "启动客户端");
                        if(MyGlobal.setting.IsWifi.get()) {
                            ip = MyGlobal.setting.ServerIpLocalHost.get();
                            port = 9999;
                        }
                        else {
                            ip = MyGlobal.setting.ServerIp.get();
                            port = 9997;
                        }
                        MyGlobal.deviceLogArrayList.add(0,new DeviceLog("准备连接服务器:"+ ip , Color.GREEN));


                        cSocket = new Socket(ip, port);

                        MyGlobal.deviceLogArrayList.add(0,new DeviceLog("已连接服务器:"+cSocket.getRemoteSocketAddress() , Color.GREEN));

                        cSocket.setSoTimeout(1000);
                        Log.i("tcp", "客户端连接成功");

                        MyGlobal.IsNetConnected = true;

                        cRecvDataThread = new RecvDataThread(cSocket);
                        cRecvDataThread.start();

                        RegClient();
                        Thread.sleep(1000);
                        GetHeart();

                        InputStream inputStream = cSocket.getInputStream();

                        byte[] buff = new byte[1024];
                        int len = -1;

                        while ((len = inputStream.read(buff)) != -1)
                        {
                            Log.i(getClass().getName(),"收到数据长度:="+len );
//                            Log.i("tcp",data);
                        }
                    }
                    catch (SocketTimeoutException ee)
                    {
                        Log.i("rqp-SocketUtil-","socket读超时异常" + ee.getMessage());
                    }
                    catch (Exception ee)
                    {
                        ee.printStackTrace();
                        Log.i("tcp","Socket异常:" + ee.getMessage());
                        MyGlobal.deviceLogArrayList.add(0,new DeviceLog("Server IP:" + ip +",Socket异常:" + ee.getMessage() , Color.RED));
                        EventBus.getDefault().post(MessageType.NetNotConnect);
                    }
                    finally {

                    }
                }
            };
            cExecutorService.execute(runnable);
        }
    }

    public void Close() {
        Log.i("rqp-SocketUtil-Close()","Socket关闭");
        try {
            if (cSocket != null) {
                cSocket.close();
                cSocket = null;
            }
        } catch (IOException ee) {
            ee.printStackTrace();
        }

        if(cRecvDataThread != null) {
            if (!cRecvDataThread.isInterrupted()) {
                cRecvDataThread.interrupt();
            }
        }
    }

    //发送命令
    private void SendSocketData(byte[] buffer,int size)
    {
        MyMessage myMessage = new MyMessage(MessageCategory.SocketSend);

        EventBus.getDefault().post(myMessage);

        if(cSocket != null &&  cSocket.isConnected())
        {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {

                    try
                    {
                        cSocket.getOutputStream().write(buffer);
                        cSocket.getOutputStream().flush();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            };
            cExecutorService.execute(runnable);
        }
    }

    //注册客户端
    public void RegClient()
    {
        long userTel = MyGlobal.setting.UserTelData;
        byte[] TmpChar = new byte[10];
        TmpChar[0] = (byte) 0xA0;
        TmpChar[1] = (byte) 0xB0;
        TmpChar[2] = (byte) 0xC0;
        TmpChar[3] = (byte) 0xD0;
        TmpChar[4] = (byte)(userTel >> 32);
        TmpChar[5] = (byte)(userTel >> 24);
        TmpChar[6] = (byte)(userTel >> 16);
        TmpChar[7] = (byte)(userTel >> 8);
        TmpChar[8] = (byte)(userTel);
        for (int i = 0; i < 9; i++) TmpChar[9] += TmpChar[i];
        SendSocketData(TmpChar, 10);
    }

    private void SetHeadData(byte[] TmpCode)
    {
        int ID = Integer.parseInt(MyGlobal.unitinfo.DTU.get());
        TmpCode[0] = (byte) 0xA2;
        TmpCode[1] = (byte) 0xB2;
        TmpCode[2] = (byte) 0xC2;
        TmpCode[3] = (byte) 0xD2;

        TmpCode[5] = (byte) (ID >> 24);
        TmpCode[6] = (byte) (ID >> 16);
        TmpCode[7] = (byte) (ID >> 8);
        TmpCode[8] = (byte) (ID);
    }
    //获取心跳
    public void GetHeart()
    {
        byte[] TmpCode = new byte[11];
        SetHeadData(TmpCode);

        TmpCode[4] = (byte) 0x06;
        TmpCode[9] = 0x01;

        byte CheckByte = 0;
        for (int j = 0; j < 10; j++) CheckByte += TmpCode[j];
        TmpCode[10] = CheckByte;
        SendSocketData(TmpCode, 11);
        MyGlobal.TimeoutCount = 55;
    }

    //系统通断电
    public void SendCmd_SYSPower(boolean isAutoCtrl,boolean sdzt)
    {
        byte[] TmpCode = new byte[14];
        SetHeadData(TmpCode);

        TmpCode[4] = (byte) 0x09;
        TmpCode[9] = (byte) 0x02;

        if (sdzt)
        {
            TmpCode[10] = 0;
        }
        else
        {
            TmpCode[10] = 1;
        }

        if(Boolean.TRUE.equals(MyGlobal.unitinfo.IsLinePower.get()))
            TmpCode[11] = 1;  //1: 市电 2:发电机
        else
            TmpCode[11] = 2;

        if(isAutoCtrl)
            TmpCode[12] = 1; // 1:自动 2:手动
        else
            TmpCode[12] = 2; // 1:自动 2:手动

        byte CheckByte = 0;
        for (int j = 0; j < 13; j++) CheckByte += TmpCode[j];
        TmpCode[13] = CheckByte;
        SendSocketData(TmpCode, 14);
    }

    public void SendCmd_FYD()
    {
        byte[] TmpCode = new byte[12];
        SetHeadData(TmpCode);

        TmpCode[4] = (byte) 0x07;
        TmpCode[9] = (byte) 0x03;

        if (MyGlobal.unitstatus.FYDZT)
        {
            TmpCode[10] = 0;
        }
        else
        {
            TmpCode[10] = 1;
        }
        byte CheckByte = 0;
        for (int j = 0; j < 11; j++) CheckByte += TmpCode[j];
        TmpCode[11] = CheckByte;
        SendSocketData(TmpCode, 12);
    }


    //俯仰
    public void SendCmd_FY()
    {
        byte[] TmpCode = new byte[12];
        SetHeadData(TmpCode);
        TmpCode[4] = (byte) 0x07;
        TmpCode[9] = (byte) 0x0A;

//        if (MyGlobal.unitstatus.FYJ > 80)
//        {
//            TmpCode[10] = 10;
//        }
//        else if (MyGlobal.unitstatus.FYJ < 10)
//        {
//            TmpCode[10] = 100;
//        }
        byte CheckByte = 0;
        for (int j = 0; j < 11; j++) CheckByte += TmpCode[j];
        TmpCode[11] = CheckByte;
        SendSocketData(TmpCode, 12);
    }


    //焰条点火
    public void SendCmd_Fire()
    {
        byte[] TmpCode = new byte[12];
        SetHeadData(TmpCode);

        TmpCode[4] = (byte) 0x07;
        TmpCode[9] = (byte)0x08;
        TmpCode[10] = 2;

        byte CheckByte = 0;
        for (int j = 0; j < 11; j++) CheckByte += TmpCode[j];
        TmpCode[11] = CheckByte;
        SendSocketData(TmpCode, 12);
    }

    //焰条复位
    public void SendCmd_FireReset()
    {
        byte[] TmpCode = new byte[11];
        SetHeadData(TmpCode);

        TmpCode[4] = (byte) 0x06;
        TmpCode[9] = (byte)0x06;

        byte CheckAByte = 0;
        for (int j = 0; j < 10; j++) CheckAByte += TmpCode[j];
        TmpCode[10] = CheckAByte;

        SendSocketData(TmpCode, 11);
    }

    //焰条巡检
    public void SendCmd_FireStatus()
    {
        byte[] TmpCode = new byte[11];
        SetHeadData(TmpCode);

        TmpCode[4] = 0x06;
        TmpCode[9] = 0x07;

        byte CheckAByte = 0;
        for (int j = 0; j < 10; j++) CheckAByte += TmpCode[j];
        TmpCode[10] = CheckAByte;
        SendSocketData(TmpCode, 11);
    }
    //设备复位
    public void SendCmd_Reset()
    {
        byte[] TmpCode = new byte[13];
        SetHeadData(TmpCode);


        TmpCode[4] = (byte) 0x07;
        TmpCode[9] = 0x10;
        TmpCode[10] = 1;

        if(Boolean.TRUE.equals(MyGlobal.unitinfo.IsLinePower.get())) //市电供电:1,发电机供电:2
            TmpCode[11] = 1;
        else
            TmpCode[11] = 2;

        byte CheckByte = 0;
        for (int j = 0; j < 12; j++) CheckByte += TmpCode[j];
        TmpCode[12] = CheckByte;
        SendSocketData(TmpCode, 13);
    }

    //急停
    public void SendCmd_AlarmStop()
    {
        byte[] TmpCode = new byte[12];
        SetHeadData(TmpCode);

        TmpCode[4] = (byte) 0x07;
        TmpCode[9] = 0x0F;

        if (MyGlobal.unitstatus.AlarmStop)
        {
            TmpCode[10] = 0;
        }
        else
        {
            TmpCode[10] = 1;
        }

        byte CheckByte = 0;
        for (int j = 0; j < 11; j++) CheckByte += TmpCode[j];
        TmpCode[11] = CheckByte;
        SendSocketData(TmpCode, 12);
    }

}
